---
title: "Reference: Agent.generate() | Agents"
description: "Documentation for the `Agent.generate()` method in Mastra agents, which enables non-streaming generation of responses with enhanced capabilities."
---

import { MODEL_SETTINGS_OBJECT } from "@site/src/components/ModelSettingsProperties";

# Agent.generate()

The `.generate()` method enables non-streaming response generation from an agent, with enhanced capabilities and flexible output formats. It accepts messages and optional generation options, supporting both Mastra’s native format and AI SDK v5 compatibility.

## Usage example

```typescript copy
// Default Mastra format
const mastraResult = await agent.generate("message for agent");

// AI SDK v5 compatible format
const aiSdkResult = await agent.generate("message for agent", {
  format: "aisdk",
});

// With model settings (e.g., limiting output tokens)
const limitedResult = await agent.generate("Write a short poem about coding", {
  modelSettings: {
    maxOutputTokens: 50,
    temperature: 0.7,
  },
});
```

:::info

**Model Compatibility**: This method is designed for V2 models. V1 models should use the [`.generateLegacy()`](./generateLegacy) method. The framework automatically detects your model version and will throw an error if there's a mismatch.

:::

## Parameters

<PropertiesTable
  content={[
    {
      name: "messages",
      type: "string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]",
      description:
        "The messages to send to the agent. Can be a single string, array of strings, or structured message objects.",
    },
    {
      name: "options",
      type: "AgentExecutionOptions<Output, Format>",
      isOptional: true,
      description: "Optional configuration for the generation process.",
    },
  ]}
/>

### Options

<PropertiesTable
  content={[
    {
      name: "format",
      type: "'mastra' | 'aisdk'",
      isOptional: true,
      defaultValue: "'mastra'",
      description:
        "Determines the output format. Use 'mastra' for Mastra's native format (default) or 'aisdk' for AI SDK v5 compatibility.",
    },
    {
      name: "maxSteps",
      type: "number",
      isOptional: true,
      description: "Maximum number of steps to run during execution.",
    },
    {
      name: "scorers",
      type: "MastraScorers | Record<string, { scorer: MastraScorer['name']; sampling?: ScoringSamplingConfig }>",
      isOptional: true,
      description: "Evaluation scorers to run on the execution results.",
      properties: [
        {
          parameters: [
            {
              name: "scorer",
              type: "string",
              isOptional: false,
              description: "Name of the scorer to use.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "sampling",
              type: "ScoringSamplingConfig",
              isOptional: true,
              description: "Sampling configuration for the scorer.",
              properties: [
                {
                  parameters: [
                    {
                      name: "type",
                      type: "'none' | 'ratio'",
                      isOptional: false,
                      description:
                        "Type of sampling strategy. Use 'none' to disable sampling or 'ratio' for percentage-based sampling.",
                    },
                  ],
                },
                {
                  parameters: [
                    {
                      name: "rate",
                      type: "number",
                      isOptional: true,
                      description:
                        "Sampling rate (0-1). Required when type is 'ratio'.",
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    },
    {
      name: "returnScorerData",
      type: "boolean",
      isOptional: true,
      description: "Whether to return detailed scoring data in the response.",
    },
    {
      name: "onChunk",
      type: "(chunk: ChunkType) => Promise<void> | void",
      isOptional: true,
      description: "Callback function called for each chunk during generation.",
    },
    {
      name: "onError",
      type: "({ error }: { error: Error | string }) => Promise<void> | void",
      isOptional: true,
      description:
        "Callback function called when an error occurs during generation.",
    },
    {
      name: "onAbort",
      type: "(event: any) => Promise<void> | void",
      isOptional: true,
      description: "Callback function called when the generation is aborted.",
    },
    {
      name: "activeTools",
      type: "Array<keyof ToolSet> | undefined",
      isOptional: true,
      description:
        "Array of tool names that should be active during execution. If undefined, all available tools are active.",
    },
    {
      name: "abortSignal",
      type: "AbortSignal",
      isOptional: true,
      description:
        "Signal object that allows you to abort the agent's execution. When the signal is aborted, all ongoing operations will be terminated.",
    },
    {
      name: "prepareStep",
      type: "PrepareStepFunction<any>",
      isOptional: true,
      description:
        "Callback function called before each step of multi-step execution.",
    },
    {
      name: "context",
      type: "ModelMessage[]",
      isOptional: true,
      description: "Additional context messages to provide to the agent.",
    },
    {
      name: "structuredOutput",
      type: "StructuredOutputOptions<S extends ZodTypeAny = ZodTypeAny>",
      isOptional: true,
      description: "Options to fine tune your structured output generation.",
      properties: [
        {
          parameters: [
            {
              name: "schema",
              type: "z.ZodSchema<S>",
              isOptional: false,
              description: "Zod schema defining the expected output structure.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "model",
              type: "MastraLanguageModel",
              isOptional: true,
              description:
                "Language model to use for structured output generation. If provided, enables the agent to respond in multi step with tool calls, text, and structured output",
            },
          ],
        },
        {
          parameters: [
            {
              name: "errorStrategy",
              type: "'strict' | 'warn' | 'fallback'",
              isOptional: true,
              description:
                "Strategy for handling schema validation errors. 'strict' throws errors, 'warn' logs warnings, 'fallback' uses fallback values.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "fallbackValue",
              type: "<S extends ZodTypeAny>",
              isOptional: true,
              description:
                "Fallback value to use when schema validation fails and errorStrategy is 'fallback'.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "instructions",
              type: "string",
              isOptional: true,
              description:
                "Additional instructions for the structured output model.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "jsonPromptInjection",
              type: "boolean",
              isOptional: true,
              description:
                "Injects system prompt into the main agent instructing it to return structured output, useful for when a model does not natively support structured outputs.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "providerOptions",
              type: "ProviderOptions",
              isOptional: true,
              description:
                "Provider-specific options passed to the internal structuring agent. Use this to control model behavior like reasoning effort for thinking models (e.g., `{ openai: { reasoningEffort: 'low' } }`).",
            },
          ],
        },
      ],
    },
    {
      name: "outputProcessors",
      type: "Processor[]",
      isOptional: true,
      description:
        "Output processors to use for this execution (overrides agent's default).",
    },
    {
      name: "inputProcessors",
      type: "Processor[]",
      isOptional: true,
      description:
        "Input processors to use for this execution (overrides agent's default).",
    },
    {
      name: "instructions",
      type: "string",
      isOptional: true,
      description:
        "Custom instructions that override the agent's default instructions for this execution.",
    },
    {
      name: "system",
      type: "string | string[] | CoreSystemMessage | SystemModelMessage | CoreSystemMessage[] | SystemModelMessage[]",
      isOptional: true,
      description:
        "Custom system message(s) to include in the prompt. Can be a single string, message object, or array of either. System messages provide additional context or behavior instructions that supplement the agent's main instructions.",
    },
    {
      name: "output",
      type: "Zod schema | JsonSchema7",
      isOptional: true,
      description:
        "**Deprecated.** Use structuredOutput without a model to achieve the same thing. Defines the expected structure of the output. Can be a JSON Schema object or a Zod schema.",
    },
    {
      name: "memory",
      type: "object",
      isOptional: true,
      description:
        "Memory configuration for conversation persistence and retrieval.",
      properties: [
        {
          parameters: [
            {
              name: "thread",
              type: "string | { id: string; metadata?: Record<string, any>, title?: string }",
              isOptional: false,
              description:
                "Thread identifier for conversation continuity. Can be a string ID or an object with ID and optional metadata/title.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "resource",
              type: "string",
              isOptional: false,
              description:
                "Resource identifier for organizing conversations by user, session, or context.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "options",
              type: "MemoryConfig",
              isOptional: true,
              description:
                "Additional memory configuration options for conversation management.",
            },
          ],
        },
      ],
    },
    {
      name: "onFinish",
      type: "StreamTextOnFinishCallback<any> | StreamObjectOnFinishCallback<OUTPUT>",
      isOptional: true,
      description:
        "Callback fired when generation completes. Type varies by format.",
    },
    {
      name: "onStepFinish",
      type: "StreamTextOnStepFinishCallback<any> | never",
      isOptional: true,
      description:
        "Callback fired after each generation step. Type varies by format.",
    },
    {
      name: "resourceId",
      type: "string",
      isOptional: true,
      description:
        "Deprecated. Use memory.resource instead. Identifier for the resource/user.",
    },
    {
      name: "telemetry",
      type: "TelemetrySettings",
      isOptional: true,
      description:
        "Settings for OTLP telemetry collection during generation (not Tracing).",
      properties: [
        {
          parameters: [
            {
              name: "isEnabled",
              type: "boolean",
              isOptional: true,
              description: "Whether telemetry collection is enabled.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "recordInputs",
              type: "boolean",
              isOptional: true,
              description: "Whether to record input data in telemetry.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "recordOutputs",
              type: "boolean",
              isOptional: true,
              description: "Whether to record output data in telemetry.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "functionId",
              type: "string",
              isOptional: true,
              description: "Identifier for the function being executed.",
            },
          ],
        },
      ],
    },
    MODEL_SETTINGS_OBJECT,
    {
      name: "threadId",
      type: "string",
      isOptional: true,
      description:
        "Deprecated. Use memory.thread instead. Thread identifier for conversation continuity.",
    },
    {
      name: "toolChoice",
      type: "'auto' | 'none' | 'required' | { type: 'tool'; toolName: string }",
      isOptional: true,
      description: "Controls how tools are selected during generation.",
      properties: [
        {
          parameters: [
            {
              name: "'auto'",
              type: "string",
              isOptional: false,
              description: "Let the model decide when to use tools (default).",
            },
          ],
        },
        {
          parameters: [
            {
              name: "'none'",
              type: "string",
              isOptional: false,
              description: "Disable tool usage entirely.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "'required'",
              type: "string",
              isOptional: false,
              description: "Force the model to use at least one tool.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "{ type: 'tool'; toolName: string }",
              type: "object",
              isOptional: false,
              description: "Force the model to use a specific tool.",
            },
          ],
        },
      ],
    },
    {
      name: "toolsets",
      type: "ToolsetsInput",
      isOptional: true,
      description: "Additional tool sets that can be used for this execution.",
    },
    {
      name: "clientTools",
      type: "ToolsInput",
      isOptional: true,
      description: "Client-side tools available during execution.",
    },
    {
      name: "savePerStep",
      type: "boolean",
      isOptional: true,
      description:
        "Save messages incrementally after each generation step completes (default: false).",
    },
    {
      name: "providerOptions",
      type: "Record<string, Record<string, JSONValue>>",
      isOptional: true,
      description: "Provider-specific options passed to the language model.",
      properties: [
        {
          parameters: [
            {
              name: "openai",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description:
                "OpenAI-specific options like reasoningEffort, responseFormat, etc.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "anthropic",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description: "Anthropic-specific options like maxTokens, etc.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "google",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description: "Google-specific options.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "[providerName]",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description: "Any provider-specific options.",
            },
          ],
        },
      ],
    },
    {
      name: "runId",
      type: "string",
      isOptional: true,
      description: "Unique identifier for this execution run.",
    },
    {
      name: "requestContext",
      type: "RequestContext",
      isOptional: true,
      description:
        "Request Context containing dynamic configuration and state.",
    },
    {
      name: "tracingContext",
      type: "TracingContext",
      isOptional: true,
      description:
        "Tracing context for creating child spans and adding metadata. Automatically injected when using Mastra's tracing system.",
      properties: [
        {
          parameters: [
            {
              name: "currentSpan",
              type: "Span",
              isOptional: true,
              description:
                "Current span for creating child spans and adding metadata. Use this to create custom child spans or update span attributes during execution.",
            },
          ],
        },
      ],
    },
    {
      name: "tracingOptions",
      type: "TracingOptions",
      isOptional: true,
      description: "Options for Tracing configuration.",
      properties: [
        {
          parameters: [
            {
              name: "metadata",
              type: "Record<string, any>",
              isOptional: true,
              description:
                "Metadata to add to the root trace span. Useful for adding custom attributes like user IDs, session IDs, or feature flags.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "requestContextKeys",
              type: "string[]",
              isOptional: true,
              description:
                "Additional RequestContext keys to extract as metadata for this trace. Supports dot notation for nested values (e.g., 'user.id').",
            },
          ],
        },
        {
          parameters: [
            {
              name: "traceId",
              type: "string",
              isOptional: true,
              description:
                "Trace ID to use for this execution (1-32 hexadecimal characters). If provided, this trace will be part of the specified trace.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "parentSpanId",
              type: "string",
              isOptional: true,
              description:
                "Parent span ID to use for this execution (1-16 hexadecimal characters). If provided, the root span will be created as a child of this span.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "tags",
              type: "string[]",
              isOptional: true,
              description:
                "Tags to apply to this trace. String labels for categorizing and filtering traces.",
            },
          ],
        },
      ],
    },
  ]}
/>

## Returns

<PropertiesTable
  content={[
    {
      name: "result",
      type: "Awaited<ReturnType<MastraModelOutput<Output>['getFullOutput']>> | Awaited<ReturnType<AISDKV5OutputStream<Output>['getFullOutput']>>",
      description:
        "Returns the full output of the generation process. When format is 'mastra' (default), returns MastraModelOutput result. When format is 'aisdk', returns AISDKV5OutputStream result for AI SDK v5 compatibility.",
    },
    {
      name: "traceId",
      type: "string",
      isOptional: true,
      description:
        "The trace ID associated with this execution when Tracing is enabled. Use this to correlate logs and debug execution flow.",
    },
  ]}
/>
